<template>
  <div class="echarts-zhexian-judian-container">
    <div class="chart-wrapper">
      <div class="line-chart" ref="lineChartRef"></div>
      <div class="coordinate-chart" ref="coordinateChartRef"></div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, onUnmounted, defineProps, watch } from 'vue'
import * as echarts from 'echarts'

// 属性定义 start
interface Props {
  // 点的坐标数组
  pointCoordinates?: number[][];
  // 四个坐标点对应的值数组
  coordinateValues?: number[][];
  // 坐标组成的集合数组
  coordinateSets?: {
    start: number;
    end: number;
    color: string;
    name: string;
  }[];
}

const props = defineProps<Props>()
// 属性定义 end

// 图表实例和DOM引用 start
const lineChartRef = ref<HTMLElement | null>(null)
const coordinateChartRef = ref<HTMLElement | null>(null)
let theLineChart: echarts.ECharts | null = null
let theCoordinateChart: echarts.ECharts | null = null
// 图表实例和DOM引用 end

// 模拟数据 start
// 模拟点的坐标数组 - x坐标
const theDefaultPointCoordinates = [
  [0, 10], [50, 10], [100, 10], [150, 10], [200, 10], [250, 10], 
  [300, 10], [350, 10], [400, 10], [450, 10], [500, 10], [550, 10],
  [600, 10], [650, 10], [700, 10], [750, 10], [800, 10], [850, 10],
  [900, 10], [950, 10], [1000, 10]
]

// 模拟四个坐标点对应的值数组 - 每个点有四个值，分别对应四条折线
const theDefaultCoordinateValues = [
  [10, 25, 40, 55], // 第一个点的四个值
  [15, 30, 45, 60], // 第二个点的四个值
  [20, 35, 50, 65], // ...
  [25, 40, 55, 70],
  [30, 45, 60, 75],
  [35, 50, 65, 80],
  [40, 55, 70, 85],
  [45, 60, 75, 90],
  [50, 65, 80, 95],
  [55, 70, 85, 100],
  [60, 75, 90, 105],
  [65, 80, 95, 110],
  [70, 85, 100, 115],
  [75, 90, 105, 120],
  [80, 95, 110, 125],
  [85, 100, 115, 130],
  [90, 105, 120, 135],
  [95, 110, 125, 140],
  [100, 115, 130, 145],
  [105, 120, 135, 150],
  [110, 125, 140, 155]
]

// 模拟坐标组成的集合数组 - 定义区域段落
const theDefaultCoordinateSets = [
  { start: 0, end: 100, color: '#FF6B6B', name: '区段A' },
  { start: 100, end: 250, color: '#4ECDC4', name: '区段B' },
  { start: 250, end: 400, color: '#FFD166', name: '区段C' },
  { start: 400, end: 550, color: '#06D6A0', name: '区段D' },
  { start: 550, end: 700, color: '#118AB2', name: '区段E' },
  { start: 700, end: 850, color: '#073B4C', name: '区段F' },
  { start: 850, end: 1000, color: '#7B68EE', name: '区段G' }
]
// 模拟数据 end

// 数据处理 start
const onGetActualData = () => {
  return {
    pointCoordinates: props.pointCoordinates || theDefaultPointCoordinates,
    coordinateValues: props.coordinateValues || theDefaultCoordinateValues,
    coordinateSets: props.coordinateSets || theDefaultCoordinateSets
  }
}

// 处理折线图数据
const onProcessLineChartData = () => {
  const { pointCoordinates, coordinateValues } = onGetActualData()
  
  // 确保数据长度一致
  if (pointCoordinates.length !== coordinateValues.length) {
    console.error('点坐标数组和值数组长度不一致')
    return {
      xAxis: [],
      series: []
    }
  }
  
  // 提取x轴坐标
  const xAxisData = pointCoordinates.map(point => point[0])
  
  // 处理系列数据 - 假设每个点有4个值，对应4条折线
  const seriesData = []
  const seriesCount = coordinateValues[0]?.length || 0
  
  for (let i = 0; i < seriesCount; i++) {
    const data = coordinateValues.map(values => values[i])
    seriesData.push({
      name: `折线${i + 1}`,
      type: 'line',
      data: data,
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2
      }
    })
  }
  
  return {
    xAxis: xAxisData,
    series: seriesData
  }
}

// 处理坐标图数据
const onProcessCoordinateChartData = () => {
  const { pointCoordinates, coordinateSets } = onGetActualData()
  
  // 提取x轴范围
  const xMin = Math.min(...pointCoordinates.map(point => point[0]))
  const xMax = Math.max(...pointCoordinates.map(point => point[0]))
  
  // 处理区域数据
  const visualMapPieces = coordinateSets.map(set => ({
    gt: set.start - 1, // 大于起始值
    lte: set.end, // 小于等于结束值
    color: set.color
  }))
  
  // 创建区域图的数据
  const areaData = []
  for (let i = 0; i < coordinateSets.length; i++) {
    const set = coordinateSets[i]
    areaData.push([
      set.start, 0, set.end, 20, set.name // x起点, y起点, x终点, y终点, 名称
    ])
  }
  
  return {
    xRange: [xMin, xMax],
    visualMapPieces,
    areaData
  }
}
// 数据处理 end

// 图表初始化和配置 start
// 初始化折线图
const onInitLineChart = () => {
  if (!lineChartRef.value) return
  
  // 初始化echarts实例
  theLineChart = echarts.init(lineChartRef.value)
  
  // 处理数据
  const { xAxis, series } = onProcessLineChartData()
  
  // 配置项
  const theOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: series.map(item => item.name),
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxis,
      axisLabel: {
        rotate: 45,
        formatter: (value: number) => value.toString()
      }
    },
    yAxis: {
      type: 'value'
    },
    series: series
  }
  
  // 设置配置项
  theLineChart.setOption(theOption)
}

// 初始化坐标图
const onInitCoordinateChart = () => {
  if (!coordinateChartRef.value) return
  
  // 初始化echarts实例
  theCoordinateChart = echarts.init(coordinateChartRef.value)
  
  // 处理数据
  const { xRange, visualMapPieces, areaData } = onProcessCoordinateChartData()
  
  // 配置项
  const theOption = {
    tooltip: {
      formatter: function(params: any) {
        const data = params.data
        return `${data[4]}: ${data[0]} - ${data[2]}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: xRange[0],
      max: xRange[1],
      axisLabel: {
        formatter: (value: number) => value.toString()
      }
    },
    yAxis: {
      type: 'value',
      show: false,
      min: 0,
      max: 20
    },
    series: [
      {
        type: 'custom',
        renderItem: function(params: any, api: any) {
          const start = api.coord([api.value(0), api.value(1)])
          const end = api.coord([api.value(2), api.value(3)])
          const height = end[1] - start[1]
          
          // 获取区域颜色
          const coordValue = api.value(0)
          let color = '#ccc'
          for (const piece of visualMapPieces) {
            if (coordValue > piece.gt && coordValue <= piece.lte) {
              color = piece.color
              break
            }
          }
          
          return {
            type: 'rect',
            shape: {
              x: start[0],
              y: start[1],
              width: end[0] - start[0],
              height: height
            },
            style: {
              fill: color
            }
          }
        },
        data: areaData,
        encode: {
          x: [0, 2], // x轴对应data中的第1个和第3个值
          y: [1, 3]  // y轴对应data中的第2个和第4个值
        }
      }
    ]
  }
  
  // 设置配置项
  theCoordinateChart.setOption(theOption)
}

// 更新图表
const onUpdateCharts = () => {
  onInitLineChart()
  onInitCoordinateChart()
}
// 图表初始化和配置 end

// 窗口大小变化处理 start
const onResizeHandler = () => {
  theLineChart?.resize()
  theCoordinateChart?.resize()
}
// 窗口大小变化处理 end

// 监听属性变化 start
watch(
  () => [props.pointCoordinates, props.coordinateValues, props.coordinateSets],
  () => {
    onUpdateCharts()
  },
  { deep: true }
)
// 监听属性变化 end

// 生命周期钩子 start
onMounted(() => {
  onUpdateCharts()
  window.addEventListener('resize', onResizeHandler)
})

onUnmounted(() => {
  window.removeEventListener('resize', onResizeHandler)
  theLineChart?.dispose()
  theCoordinateChart?.dispose()
  theLineChart = null
  theCoordinateChart = null
})
// 生命周期钩子 end
</script>

<style lang="scss" scoped>
.echarts-zhexian-judian-container {
  width: 100%;
  height: 100%;
  
  .chart-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    
    .line-chart {
      width: 100%;
      height: 300px;
    }
    
    .coordinate-chart {
      width: 100%;
      height: 100px;
      margin-top: 10px;
    }
  }
}
</style>